import json

import pika


class RabbitMQClient:
    def __init__(self, server_mq_url, server_mq_out):
        self.server_mq_url = server_mq_url
        self.server_mq_out = server_mq_out
        self.rabbitmq_parameters = pika.URLParameters(self.server_mq_url)


    def publish_msg(self, out, body):
        rabbitmq_connection = pika.BlockingConnection(self.rabbitmq_parameters)
        rabbitmq_channel = rabbitmq_connection.channel()
        # 发送fanout
        if out is None or out == "":
            out = self.server_mq_out

        # 声明一个 fanout 类型的 exchange
        rabbitmq_channel.exchange_declare(exchange=out, exchange_type='fanout')
        # 发送消息到指定的 fanout exchange
        rabbitmq_channel.basic_publish(exchange=out, routing_key='', body=json.dumps(body))
        rabbitmq_connection.close()

if __name__ == '__main__':
    rabbitmq_client = RabbitMQClient('amqp://guest:guest@192.168.110.135:5672', "logs")
    rabbitmq_client.publish_msg("", 'Hello World!')
